<template>
  <div id="app">
    <div id="mapbox"
         class="mapbox"></div>
    <!-- current-floor -->
    <div class="current-floor"
         v-on:click="toggleIsActive">{{currentFloorNumber}}</div>
    <!-- select-floor-box -->
    <div :class="[isActive ? 'activeClass' : 'hidden','select-floor-box']">
      <div class="title">切换楼层</div>
      <ul class="floors">
        <li v-for="item in site.floors"
            :key="item.floorId"
            :class="{active: currentFloorId === item.floorId}"><span class="number">{{item.floorNumber}}</span><span class="name">{{item.floorName}}</span></li>
      </ul>
    </div>
    <!-- handle-left -->
    <div class="handle-l">
      <ul class="list">
        <li>指南</li>
        <li>定位</li>
        <li>驾车</li>
        <li>公交</li>
      </ul>
    </div>
    <!-- handle-right -->
    <div class="handle-r">
      <ul class="list">
        <li>设置</li>
        <li>语音</li>
        <li>pitch</li>
        <li>3D</li>
      </ul>
    </div>
  </div>
</template>

<script>
import mapboxgl from 'mapbox-gl'
import sitedata from './assets/js/siteData'
import axios from 'axios'
import utils from './assets/js/utils'
export default {
  name: 'App',
  data() {
    return {
      site: sitedata.siteInfo,
      currentFloorId: sitedata.siteInfo.defaultFloorId,
      currentFloorNumber: sitedata.siteInfo.defaultFloorNumber,
      siteFloors: {
        floorsMetadata: {},
        floorsMap: {},
        currentFloorId: sitedata.siteInfo.defaultFloorId,
      },
      isActive: false, //默认隐藏楼层选择
    }
  },
  methods: {
    // 切换选择楼层显示/隐藏
    toggleIsActive() {
      console.log(this.site)
      this.isActive = !this.isActive ? true : false
    },
  },
  mounted() {
    var _this = this
    mapboxgl.accessToken =
      'pk.eyJ1IjoiZmlnaHhwIiwiYSI6ImNrbzQwanE5NjE3ZWIydnA5MTV4amFpNDcifQ.o1sqvH-u9edNqv_eNpv9SA'
    var map = new mapboxgl.Map({
      container: 'mapbox', // container ID
      style: 'mapbox://styles/fighxp/ckr2tem535y9918quwb9cf4u9', // style URL
      center: [114.217175463262365, 30.771448523487603],
      zoom: 16,
      maxZoom: 24,
      pitch: 30,
      // pitch: 0,
    })
    map.on('click', function () {
      console.log(_this)
      _this.isActive = false
    })
    map.addControl(new mapboxgl.NavigationControl())

    //当前楼层
    const currentFloor = utils.getArrFirstItem(this.site.floors)
    Promise.all([
      axios.get(currentFloor.polygons[0].url),
      axios.get(currentFloor.polygons[1].url),
      axios.get(currentFloor.points.markers.url),
    ]).then((data) => {
      let dataArr = utils.getArrDataItem(data)
      let [outlinePolygon, shopsPolygon, consMarkers] = [...dataArr]
      console.log(outlinePolygon)
      console.log(shopsPolygon)
      console.log(consMarkers)

      map.on('load', function () {
        // Add a data source containing GeoJSON data.
        map.addSource('maine', {
          type: 'geojson',
          data: outlinePolygon,
        })

        // Add a new layer to visualize the polygon.
        map.addLayer({
          id: 'maine',
          type: 'fill',
          source: 'maine', // reference the data source
          layout: {},
          paint: {
            'fill-color': '#0080ff', // blue color fill
            'fill-opacity': 0.5,
          },
        })
        // Add a black outline around the polygon.
        map.addLayer({
          id: 'outline',
          type: 'line',
          source: 'maine',
          layout: {},
          paint: {
            'line-color': '#000',
            'line-width': 3,
          },
        })
        /**-----------------------------------------3d */
        map.addSource('shops', {
          type: 'geojson',
          data: shopsPolygon,
        })

        // Add a new layer to visualize the polygon.
        map.addLayer({
          id: 'shops',
          type: 'fill-extrusion',
          source: 'shops', // reference the data source
          layout: {},
          paint: {
            'fill-extrusion-base': 20,
            'fill-extrusion-height': 60,
            'fill-extrusion-color': '#ffcc66',
            'fill-extrusion-opacity': 0.8,
            'fill-extrusion-translate': [0, 0],
            'fill-extrusion-translate-anchor': 'viewport',
            'fill-extrusion-vertical-gradient': true,
          },
        })

        /*-------------------添加点聚合--------------------------*/

        map.addSource('earthquakes', {
          type: 'geojson',
          // Point to GeoJSON data. This example visualizes all M1.0+ earthquakes
          // from 12/22/15 to 1/21/16 as logged by USGS' Earthquake hazards program.
          data: consMarkers,
          cluster: true,
          //clusterMaxZoom: 15,
          clusterRadius: 50,
        })

        map.addLayer({
          id: 'clusters',
          type: 'circle',
          source: 'earthquakes',
          filter: ['has', 'point_count'],
          paint: {
            // Use step expressions (https://docs.mapbox.com/mapbox-gl-js/style-spec/#expressions-step)
            // with three steps to implement three types of circles:
            //   * Blue, 20px circles when point count is less than 100
            //   * Yellow, 30px circles when point count is between 100 and 750
            //   * Pink, 40px circles when point count is greater than or equal to 750
            'circle-color': [
              'step',
              ['get', 'point_count'],
              '#51bbd6',
              3,
              '#f1f075',
              6,
              '#f28cb1',
            ],
            'circle-radius': [
              'step',
              ['get', 'point_count'],
              10,
              20,
              30,
              40,
              50,
            ],
          },
        })

        map.addLayer({
          id: 'cluster-count',
          type: 'symbol',
          source: 'earthquakes',
          filter: ['has', 'point_count'],
          layout: {
            'text-field': '{point_count_abbreviated}',
            'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
            'text-size': 12,
          },
        })

        map.addLayer({
          id: 'unclustered-point',
          type: 'circle',
          source: 'earthquakes',
          filter: ['!', ['has', 'point_count']],
          paint: {
            'circle-color': '#11b4da',
            'circle-radius': 4,
            'circle-stroke-width': 1,
            'circle-stroke-color': '#fff',
          },
        })

        // inspect a cluster on click
        map.on('click', 'clusters', function (e) {
          var features = map.queryRenderedFeatures(e.point, {
            layers: ['clusters'],
          })
          var clusterId = features[0].properties.cluster_id
          map
            .getSource('earthquakes')
            .getClusterExpansionZoom(clusterId, function (err, zoom) {
              if (err) return

              map.easeTo({
                center: features[0].geometry.coordinates,
                zoom: zoom,
              })
            })
        })

        // When a click event occurs on a feature in
        // the unclustered-point layer, open a popup at
        // the location of the feature, with
        // description HTML from its properties.
        map.on('click', 'unclustered-point', function (e) {
          var coordinates = e.features[0].geometry.coordinates.slice()
          var mag = e.features[0].properties.mag
          var tsunami

          if (e.features[0].properties.tsunami === 1) {
            tsunami = 'yes'
          } else {
            tsunami = 'no'
          }

          // Ensure that if the map is zoomed out such that
          // multiple copies of the feature are visible, the
          // popup appears over the copy being pointed to.
          while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
            coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360
          }

          new mapboxgl.Popup()
            .setLngLat(coordinates)
            .setHTML(
              'magnitude: ' + mag + '<br>Was there a tsunami?: ' + tsunami
            )
            .addTo(map)
        })

        map.on('mouseenter', 'clusters', function () {
          map.getCanvas().style.cursor = 'pointer'
        })
        map.on('mouseleave', 'clusters', function () {
          map.getCanvas().style.cursor = ''
        })
      })
    })
  },
  components: {},
}
</script>

<style scoped>
.mapbox {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
}
</style>
